
import MenuToggle from '../components/MenuToggle';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHeader, TableRow, TableHead } from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import React, { useState } from 'react';
import { DialogContent, DialogTitle, DialogFooter, Dialog, DialogHeader, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { MoreVertical, Edit, FileText, Code, ExternalLink, Eye, Trash2, Play, Filter, Copy, Globe, Search, Database, Plus, Settings } from 'lucide-react';
import { DropdownMenuItem, DropdownMenuTrigger, DropdownMenuContent, DropdownMenu } from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
const ApiManagement = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedApis, setSelectedApis] = useState([]);
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterMethod, setFilterMethod] = useState('all');
  const [showCreateDialog, setShowCreateDialog] = useState(false);

  // 模拟API数据
  const [apis, setApis] = useState([
    {
      id: 1,
      name: '用户信息查询',
      path: '/api/v1/users/{id}',
      method: 'GET',
      status: 'active',
      description: '根据用户ID获取用户详细信息',
      category: '用户管理',
      version: 'v1.0',
      createTime: '2024-01-15',
      updateTime: '2024-01-20',
      callCount: 1250,
      responseTime: 120
    },
    {
      id: 2,
      name: '创建用户',
      path: '/api/v1/users',
      method: 'POST',
      status: 'active',
      description: '创建新用户账户',
      category: '用户管理',
      version: 'v1.0',
      createTime: '2024-01-10',
      updateTime: '2024-01-18',
      callCount: 856,
      responseTime: 200
    },
    {
      id: 3,
      name: '文件上传',
      path: '/api/v1/files/upload',
      method: 'POST',
      status: 'active',
      description: '上传文件到服务器',
      category: '文件管理',
      version: 'v1.2',
      createTime: '2024-01-08',
      updateTime: '2024-01-19',
      callCount: 2340,
      responseTime: 350
    },
    {
      id: 4,
      name: '获取文件列表',
      path: '/api/v1/files',
      method: 'GET',
      status: 'deprecated',
      description: '获取用户文件列表',
      category: '文件管理',
      version: 'v1.0',
      createTime: '2024-01-05',
      updateTime: '2024-01-16',
      callCount: 3420,
      responseTime: 80
    },
    {
      id: 5,
      name: '删除文件',
      path: '/api/v1/files/{id}',
      method: 'DELETE',
      status: 'maintenance',
      description: '删除指定文件',
      category: '文件管理',
      version: 'v1.1',
      createTime: '2024-01-12',
      updateTime: '2024-01-17',
      callCount: 567,
      responseTime: 150
    }
  ]);

  const [newApi, setNewApi] = useState({
    name: '',
    path: '',
    method: 'GET',
    description: '',
    category: '',
    version: 'v1.0',
    status: 'active'
  });

  // 过滤API数据
  const filteredApis = apis.filter(api => {
    const matchesSearch = api.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         api.path.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         api.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || api.status === filterStatus;
    const matchesMethod = filterMethod === 'all' || api.method === filterMethod;
    return matchesSearch && matchesStatus && matchesMethod;
  });

  const handleApiSelect = (apiId) => {
    setSelectedApis(prev => 
      prev.includes(apiId) 
        ? prev.filter(id => id !== apiId)
        : [...prev, apiId]
    );
  };

  const handleSelectAll = () => {
    if (selectedApis.length === filteredApis.length) {
      setSelectedApis([]);
    } else {
      setSelectedApis(filteredApis.map(api => api.id));
    }
  };

  const handleCreateApi = () => {
    const id = Math.max(...apis.map(a => a.id)) + 1;
    const currentTime = new Date().toISOString().split('T')[0];
    
    setApis(prev => [...prev, {
      ...newApi,
      id,
      createTime: currentTime,
      updateTime: currentTime,
      callCount: 0,
      responseTime: 0
    }]);
    
    setNewApi({
      name: '',
      path: '',
      method: 'GET',
      description: '',
      category: '',
      version: 'v1.0',
      status: 'active'
    });
    setShowCreateDialog(false);
  };

  const handleDeleteApi = (apiId) => {
    setApis(prev => prev.filter(api => api.id !== apiId));
    setSelectedApis(prev => prev.filter(id => id !== apiId));
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      active: { color: 'bg-green-100 text-green-800', text: '正常' },
      deprecated: { color: 'bg-yellow-100 text-yellow-800', text: '已废弃' },
      maintenance: { color: 'bg-red-100 text-red-800', text: '维护中' },
      beta: { color: 'bg-blue-100 text-blue-800', text: '测试版' }
    };
    
    const config = statusConfig[status] || statusConfig.active;
    return (
      <Badge className={`${config.color} hover:${config.color}`}>
        {config.text}
      </Badge>
    );
  };

  const getMethodBadge = (method) => {
    const methodConfig = {
      GET: { color: 'bg-blue-100 text-blue-800' },
      POST: { color: 'bg-green-100 text-green-800' },
      PUT: { color: 'bg-orange-100 text-orange-800' },
      DELETE: { color: 'bg-red-100 text-red-800' },
      PATCH: { color: 'bg-purple-100 text-purple-800' }
    };
    
    const config = methodConfig[method] || methodConfig.GET;
    return (
      <Badge className={`${config.color} hover:${config.color} font-mono`}>
        {method}
      </Badge>
    );
  };

  const activeCount = apis.filter(a => a.status === 'active').length;
  const deprecatedCount = apis.filter(a => a.status === 'deprecated').length;
  const maintenanceCount = apis.filter(a => a.status === 'maintenance').length;
  const totalCalls = apis.reduce((sum, api) => sum + api.callCount, 0);

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl flex items-center justify-center">
                  <Code className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    API管理
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理和监控系统API接口
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索API..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={filterMethod} onValueChange={setFilterMethod}>
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部方法</SelectItem>
                  <SelectItem value="GET">GET</SelectItem>
                  <SelectItem value="POST">POST</SelectItem>
                  <SelectItem value="PUT">PUT</SelectItem>
                  <SelectItem value="DELETE">DELETE</SelectItem>
                </SelectContent>
              </Select>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="active">正常</SelectItem>
                  <SelectItem value="deprecated">已废弃</SelectItem>
                  <SelectItem value="maintenance">维护中</SelectItem>
                </SelectContent>
              </Select>

              <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
                <DialogTrigger asChild>
                  <Button className="bg-primary hover:bg-primary-600">
                    <Plus className="w-4 h-4 mr-2" />
                    新建API
                  </Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-lg">
                  <DialogHeader>
                    <DialogTitle>新建API接口</DialogTitle>
                  </DialogHeader>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="name">接口名称</Label>
                      <Input
                        id="name"
                        value={newApi.name}
                        onChange={(e) => setNewApi(prev => ({ ...prev, name: e.target.value }))}
                        placeholder="请输入接口名称"
                      />
                    </div>
                    <div>
                      <Label htmlFor="path">接口路径</Label>
                      <Input
                        id="path"
                        value={newApi.path}
                        onChange={(e) => setNewApi(prev => ({ ...prev, path: e.target.value }))}
                        placeholder="例如: /api/v1/users"
                      />
                    </div>
                    <div>
                      <Label htmlFor="method">请求方法</Label>
                      <Select value={newApi.method} onValueChange={(value) => setNewApi(prev => ({ ...prev, method: value }))}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="GET">GET</SelectItem>
                          <SelectItem value="POST">POST</SelectItem>
                          <SelectItem value="PUT">PUT</SelectItem>
                          <SelectItem value="DELETE">DELETE</SelectItem>
                          <SelectItem value="PATCH">PATCH</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div>
                      <Label htmlFor="description">接口描述</Label>
                      <Textarea
                        id="description"
                        value={newApi.description}
                        onChange={(e) => setNewApi(prev => ({ ...prev, description: e.target.value }))}
                        placeholder="请输入接口描述"
                        rows={3}
                      />
                    </div>
                    <div>
                      <Label htmlFor="category">接口分类</Label>
                      <Input
                        id="category"
                        value={newApi.category}
                        onChange={(e) => setNewApi(prev => ({ ...prev, category: e.target.value }))}
                        placeholder="例如: 用户管理"
                      />
                    </div>
                    <div>
                      <Label htmlFor="version">版本号</Label>
                      <Input
                        id="version"
                        value={newApi.version}
                        onChange={(e) => setNewApi(prev => ({ ...prev, version: e.target.value }))}
                        placeholder="例如: v1.0"
                      />
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setShowCreateDialog(false)}>
                      取消
                    </Button>
                    <Button onClick={handleCreateApi}>
                      创建API
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总接口数</p>
                  <p className="text-2xl font-bold text-material-grey-900">{apis.length}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Code className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">正常运行</p>
                  <p className="text-2xl font-bold text-green-600">{activeCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <Globe className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">维护中</p>
                  <p className="text-2xl font-bold text-red-600">{maintenanceCount}</p>
                </div>
                <div className="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                  <Settings className="w-6 h-6 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总调用次数</p>
                  <p className="text-2xl font-bold text-purple-600">{totalCalls.toLocaleString()}</p>
                </div>
                <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Database className="w-6 h-6 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* API列表 */}
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">
                    <input
                      type="checkbox"
                      checked={selectedApis.length === filteredApis.length && filteredApis.length > 0}
                      onChange={handleSelectAll}
                      className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                    />
                  </TableHead>
                  <TableHead>接口信息</TableHead>
                  <TableHead>方法</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>分类</TableHead>
                  <TableHead>调用次数</TableHead>
                  <TableHead>响应时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredApis.map((api) => (
                  <TableRow key={api.id}>
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selectedApis.includes(api.id)}
                        onChange={() => handleApiSelect(api.id)}
                        className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                      />
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center space-x-3">
                          <div className="w-8 h-8 bg-gradient-to-br from-blue-100 to-blue-200 rounded-lg flex items-center justify-center">
                            <Code className="w-4 h-4 text-blue-600" />
                          </div>
                          <div>
                            <p className="font-medium text-material-grey-900">{api.name}</p>
                            <p className="text-sm text-material-grey-500 font-mono">{api.path}</p>
                          </div>
                        </div>
                        <p className="text-xs text-material-grey-600 ml-11">{api.description}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      {getMethodBadge(api.method)}
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(api.status)}
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{api.category}</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{api.callCount.toLocaleString()}</span>
                    </TableCell>
                    <TableCell>
                      <span className="text-sm text-material-grey-700">{api.responseTime}ms</span>
                    </TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon">
                            <MoreVertical className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem>
                            <Eye className="w-4 h-4 mr-2" />
                            查看详情
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            <Play className="w-4 h-4 mr-2" />
                            测试接口
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            <Copy className="w-4 h-4 mr-2" />
                            复制路径
                          </DropdownMenuItem>
                          <DropdownMenuItem>
                            <Edit className="w-4 h-4 mr-2" />
                            编辑
                          </DropdownMenuItem>
                          <DropdownMenuItem 
                            onClick={() => handleDeleteApi(api.id)}
                            className="text-red-600"
                          >
                            <Trash2 className="w-4 h-4 mr-2" />
                            删除
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {filteredApis.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <Code className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  {searchQuery ? '未找到匹配的API' : '暂无API接口'}
                </h3>
                <p className="text-material-grey-500">
                  {searchQuery ? '尝试使用不同的关键词搜索' : '点击上方按钮开始创建API接口'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </>
  );
};

export default ApiManagement;
